import { h } from "vue";
import { Button, Space, Modal } from "ant-design-vue";
import { isFunction } from "@/utils/is";
import { real } from "@/utils";

function renderButtons(formActions: any, ctx: any) {
  formActions = real(formActions);
  if(formActions.slot) {
    if (ctx.slots[formActions.slot]) {
      return ctx.slots[formActions.slot]();
    }
  }
  return h(Space, {}, {
    default: () => formActions.map(action => renderButton(real(action)))
  });
}

function renderButton(action: any) {
  if (action.confirm && action.confirmTitle) {
    return h(Button, {
      ...action,
      icon: action.icon && h(action.icon),
      onClick: () => {
        Modal.confirm({
          title: action.confirmTitle,
          content: action.confirmInfo,
          okText: '确认',
          cancelText: '取消',
          onOk() {
            if(action.confirm) action.confirm();
          },
          onCancel() {
            if(action.cancel) action.cancel();
          }
        });
      }
    }, { default: () => [action.title] });
  }

  return h(Button, {
    ...action,
    icon: action.icon && h(action.icon)
  }, { default: () => [action.title] });
}

export default function(ctx: any): any {
  // const {slots} = ctx
  if (!ctx.attrs.formActions) return undefined;
  return h("div", {
    style: {
      background: "white",
      padding: "10px",
      margin: "10px 0"
    }
  }, renderButtons(isFunction(real(ctx.attrs.formActions)) ? ctx.attrs.formActions() : ctx.attrs.formActions, ctx));
};


